package com.bckj.fastboot.core.extra.relational;

import com.bckj.fastboot.core.extra.relational.configuration.RelationalGlobalConfig;
import com.bckj.fastboot.core.sql.Sql;
import com.bckj.fastboot.core.sql.SqlCondition;
import org.springframework.data.domain.Pageable;

import java.util.function.Consumer;

/**
 * Query
 *
 * @author wfc
 **/
public class Query {
    private Sql sql;
    private String countSql;
    private Criteria criteria;
    private Pageable pageable = Pageable.unpaged();
    private Integer skip;
    private Integer limit;

    private SqlCondition whereCondition;

    public static Query query(Sql sql) {
        Query query = new Query();
        query.sql = sql;
        return query;
    }

    private Query() {
        whereCondition = RelationalGlobalConfig.getInstance().getWhereCondition();
    }

    public Query countSql(String countSql) {
        this.countSql = countSql;
        return this;
    }

    public Query with(Pageable pageable) {
        this.pageable = pageable;
        return this;
    }

    public Query with(Integer skip, Integer limit) {
        this.skip = skip;
        this.limit = limit;
        return this;
    }

    public Query whereCondition(SqlCondition whereCondition) {
        this.whereCondition = whereCondition;
        return this;
    }

    public Query criteria(Consumer<Criteria> consumer) {
        this.criteria =  Criteria.of(sql.getWheres()).whereCondition(whereCondition);
        consumer.accept(this.criteria);
        return this;
    }

    public Sql sql() {
        return sql;
    }

    public String countSql() {
        return countSql;
    }

    public Pageable pageable() {
        return pageable;
    }

    public Criteria criteria() {
        return criteria;
    }

    public Integer skip() {
        return skip;
    }

    public Integer limit() {
        return limit;
    }

}
